package gmew.server;

import gmew.client.GmewService;
import gmew.server.entities.Item;
import gmew.shared.ItemDTO;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GmewServiceImpl extends RemoteServiceServlet implements
		GmewService {

	private PersistenceManager pm = PMF.get().getPersistenceManager();

	@SuppressWarnings("unchecked")
	@Override
	public List<ItemDTO> getAllItems() {
		String query = "select from " + Item.class.getName();
		List<Item> list = (List<Item>) pm.newQuery(query).execute();
		ArrayList<ItemDTO> newlist = new ArrayList<ItemDTO>();
		for (Item i : list)
			newlist.add(i.toItemDTO());
		return newlist;
	}

	@Override
	public void addItemFromWowhead(int id) {
		try {
			URL url = new URL("http://wowhead.com/item=" + id + "&xml");
			InputStreamReader isr = new InputStreamReader(url.openStream());
			BufferedReader reader = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new StringReader(sb.toString()));
			Element root = doc.getRootElement();
			String name = root.getChild("item").getChildText("name");

			Item i = new Item();
			i.setId(id);
			i.setName(name);
			i.setRawXml(sb.toString());
			pm.makePersistent(i);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getArmoryCharacter(String region, String server, String toon) {
		try {
			URL url = new URL("http://" + region
					+ ".wowarmory.com/character-sheet.xml?r=" + server + "&cn="
					+ toon);
			InputStreamReader isr = new InputStreamReader(url.openStream());
			BufferedReader reader = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
